package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.apis.wemedia.WmchannelClient;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.HotArticleService;
import com.heima.common.constants.ArticleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.vos.HotArticleVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.pojos.WmChannel;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class HotArticleServiceImpl implements HotArticleService {

    @Autowired
    private ApArticleMapper apArticleMapper;

    @Autowired
    private WmchannelClient wmchannelClient;

    @Autowired
    private CacheService cacheService;
    /**
     * 计算热点文章
     */
    @Override
    public void computeHotArticle() {
        //1. 查询过去5天的数据
        Date date = DateTime.now().minusDays(5).toDate();
        List<ApArticle> list = apArticleMapper.findLast5Days(date);

        //2. 计算所有文章的得分
        List<HotArticleVo> hotArticleVoList = computeHotArticleScore(list);

        //3. 缓存每个频道的数据到redis 包含了推荐的缓存数据
        cacheHotAriticle(hotArticleVoList);
    }

    //缓存数据到redis
    private void cacheHotAriticle(List<HotArticleVo> hotArticleVoList) {
        //1. 查询所有的频道
        ResponseResult responseResult = wmchannelClient.findAll();

        //2. 判断频道数据是否查询到 如果查询到了就反序列化成对象
        if(null != responseResult && responseResult.getCode().equals(200)){
            //反序列化成对象
            String json = JSON.toJSONString(responseResult.getData());
            List<WmChannel> channelList = JSON.parseArray(json, WmChannel.class);

            //3. 遍历每一个频道 找到当前频道的所有的文章数据
            for (WmChannel wmChannel : channelList) {
                List<HotArticleVo> voList = hotArticleVoList.stream()
                        .filter(x -> wmChannel.getId().equals(x.getChannelId()))
                        .collect(Collectors.toList());
                //4. 排序并且缓存到reds
                sortedAndCache(voList, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + wmChannel.getId());
            }

            //5. 缓存推荐的数据
            sortedAndCache(hotArticleVoList, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + ArticleConstants.DEFAULT_TAG);
        }
    }

    private void sortedAndCache(List<HotArticleVo> voList, String key) {
        if(null != voList && voList.size() > 0){
            voList = voList.stream()
                    .sorted(Comparator.comparing(HotArticleVo::getScore).reversed())
                    .limit(30)
                    .collect(Collectors.toList());

            cacheService.set(key, JSON.toJSONString(voList));
        }
    }

    //计算所有文章的得分
    private List<HotArticleVo> computeHotArticleScore(List<ApArticle> list) {
        if(null != list && list.size() > 0){
            List<HotArticleVo> voList = new ArrayList<>(list.size());

            for (ApArticle apArticle : list) {
                HotArticleVo vo = new HotArticleVo();
                BeanUtils.copyProperties(apArticle, vo);
                vo.setScore(computeScore(apArticle));

                voList.add(vo);
            }

            return voList;
        }

        return new ArrayList<>(0);
    }

    //计算文章的得分
    private Integer computeScore(ApArticle apArticle) {
        int score = 0;

        if(null != apArticle.getViews()){
            score += apArticle.getViews();
        }

        if(null != apArticle.getLikes()){
            score += apArticle.getLikes() * ArticleConstants.HOT_ARTICLE_LIKE_WEIGHT;
        }

        if(null != apArticle.getComment()){
            score += apArticle.getComment() * ArticleConstants.HOT_ARTICLE_COMMENT_WEIGHT;
        }

        if(null != apArticle.getCollection()){
            score += apArticle.getCollection() * ArticleConstants.HOT_ARTICLE_COLLECTION_WEIGHT;
        }

        return score;
    }
}
